package jsmc.opendata.nantes.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import jsmc.opendata.nantes.exceptions.ApiReseauException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class CheckVersionOpenData {
    /**
     * Connecteur.
     */
    private Connecteur connecteur;
    private final static String OPENDATA_API_DATA_URL = "http://data.nantes.fr/api/datastore_getdatasets/1.0/";
    private final static String OPENDATA_APPID = "JL90XICUCC5IN0X";
    
	public CheckVersionOpenData() {
		
		
	}
	
	private static String GetOpenDataUrl(String app_id,int data_id) {
		
		return OPENDATA_API_DATA_URL+ app_id +"?param[ids]=" + Integer.toString(data_id) + "&output=json";
 
	}
	
	public OpenDataCheck CheckVersion(int data_id) throws ApiReseauException {

   		try {
   			
   			String url = GetOpenDataUrl(OPENDATA_APPID,data_id);
   			InputStream inputStream = connecteur.openInputStream(url);
   			String response_str = convertStreamToString(inputStream).trim();
   			
   			JSONObject response = new JSONObject(response_str);
   		
   			
   			if (!response.has("opendata")) return null;
   			
   				
   			response = response.getJSONObject("opendata");
   			
   			if (!response.has("answer")) return null;
   			
   			response = response.getJSONObject("answer");
   			
   			
   			if (!response.has("data")) return null;
   			
   			response = response.getJSONObject("data");
   			
   			if (!response.has("dataset")) return null;
   			
   			response = response.getJSONObject("dataset");
   			
   			if (!response.has("updated")) return null;
   			
   			String date_str = response.getString("updated");
   			
   			
   			SimpleDateFormat date_parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");  
   			//date_parser.setTimeZone(TimeZone.getTimeZone("UTC"));  
   			Date local_date;
   			
   			try {
				local_date  = date_parser.parse(date_str);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				return null;
			}  
   		    
   		    
   		      
   		    if (!response.has("files")) return null;
   			
   			response = response.getJSONObject("files");
   		    
   			
   		    if (!response.has("file")) return null;
   			
   			JSONArray urls = response.getJSONArray("file");
   		    
   			String url_csv = null;
   			
   			for (int i_url=0;i_url<urls.length();i_url++) {
   				
   				JSONObject url_obj = urls.getJSONObject(i_url);
   				if (url_obj.has("format")) {
   					
   					if (url_obj.getString("format").equals("CSV")) {
   						url_csv = url_obj.getString("url");
   						
   						
   					}
   				}
   			}
   			
   			
   			if (url_csv==null) return null;
   			
   			return new OpenDataCheck(local_date.getTime(),url_csv);
   			//return new Long(local_date.getTime());
   		    
   		} catch (JSONException e) {
   			// TODO Auto-generated catch block
   			
   		}
	   		
		return null;
	}
	
    private static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}
